import { getCookie, parseCookie } from '~/utils/cookie'

export default function ({ app, req, store, redirect }) {
  // 获取token
  const token = process.server ? parseCookie(req.headers.cookie).token : getCookie('token')
  // 验证逻辑
  if (token) {
    return app.$axios.get('/user/v1/account', {
      // 获取用户信息
      headers: { 'Authorization': `Bearer${token}` }
    }).then(res => {
      if (res.data.code === 100) {
        store.dispatch('saveUserInfo', res.data.result)
      } else {
        store.dispatch('clearUserInfo')
        redirect('/login')
      }
    })
  } else {
    store.dispatch('clearUserInfo')
    redirect('/login')
  }
}
